package com.shopping.mall.core.module.paypal.controller;


import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import com.shopping.mall.auth.annotation.UnLogin;
import com.shopping.mall.auth.utils.UserUtils;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.state.OrderState;
import com.shopping.mall.base.util.WrapperUtils;
import com.shopping.mall.core.module.order.entity.Order;
import com.shopping.mall.core.module.order.mapper.OrderMapper;
import com.shopping.mall.core.module.order.service.MailService;
import com.shopping.mall.core.module.order.service.OrderService;
import com.shopping.mall.core.module.paypal.entity.PaymentModel;
import com.shopping.mall.core.module.paypal.service.PaymentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @program: 
 * @description:
 * @author: 
 * @create: 
 **/

@Api(tags = "支付")
@Controller
@RequestMapping("/order")
public class PaymentController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MailService mailService;

    @Value("${paypal.backHost}")
    private String backHost;

    @Value("${paypal.host}")
    private String host;


    /**
     * 成功页面
     */
    public static final String PAYPAL_SUCCESS_URL = "pay/success";

    /**
     * 取消页面
     */
    public static final String PAYPAL_CANCEL_URL = "pay/cancel";

    @Autowired
    private PaymentService paymentService;

    @GetMapping("/paypal")
    public String index(){
        return "index";
    }


//    @UnLogin
    @ResponseBody
    @PostMapping("/pay")
    public Result<String> payment(@RequestBody Order order, HttpServletRequest request){
//        获取取消页面
        try {
            String cancelUrl = backHost+ "/order/" + PAYPAL_CANCEL_URL;
            //获取成功页面
            String successUrl = backHost+ "/order/" + PAYPAL_SUCCESS_URL;
            Payment payment = null;
            PaymentModel paymentModel = new PaymentModel();
            Order oldOrder=orderService.getById(order.getId());
            System.out.println(oldOrder);
            if(oldOrder==null){
                return Result.error(ResponseState.ORDER_NOT_EXIST.getValue(),ResponseState.ORDER_NOT_EXIST.getMessage());
            }
            if(!oldOrder.getUserId().equals(UserUtils.getLoginUserId())){
                return Result.error(ResponseState.WITHOUT_PERMISSION.getValue(), ResponseState.WITHOUT_PERMISSION.getMessage());
            }
            if(oldOrder.getState()!=OrderState.START.getValue()){
                return Result.error(ResponseState.ORDER_NOT_MATCH.getValue(),ResponseState.ORDER_NOT_MATCH.getMessage());
            }
            //金额
            paymentModel.setAmount(String.valueOf(oldOrder.getTotalPrice()));
            //金额类型
            paymentModel.setCurrency("USD");
            //充值描述
            paymentModel.setDescription("payment description");
            try {
                payment = paymentService.createPayment(paymentModel, cancelUrl, successUrl);
                oldOrder.setOutTradeNo(payment.getId());
                orderMapper.updateById(oldOrder);
            } catch (PayPalRESTException e) {
                e.printStackTrace();
            }
            for(Links links : payment.getLinks()){
                System.out.println(links.getRel());
                if(links.getRel().equals("approval_url")){
                    //客户付款登陆地址
                   return Result.OK(links.getHref());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error(ResponseState.PAY_ERROR.getValue(),ResponseState.PAY_ERROR.getMessage());
    }

    /**
     * 取消页面
     */
    @UnLogin
    @GetMapping(value = PAYPAL_CANCEL_URL)
    public String cancelPay(){
        return "redirect:"+host+"/#/fail/order/pay";
    }

    /**
     * 执行支付
     */
    @UnLogin
    @GetMapping(value = PAYPAL_SUCCESS_URL)
    public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
        Payment payment = null;
        try {
            payment = paymentService.executePayment(paymentId, payerId);
        } catch (PayPalRESTException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(payment.getState().equals("approved")){
            com.shopping.mall.core.module.order.entity.Order oldOrder=orderMapper.selectOne(WrapperUtils.getQueryWrapper("out_trade_no",paymentId));
            oldOrder.setState(OrderState.COPY_SUCCESS.getValue());
            oldOrder.setPayAt(new Timestamp(new Date().getTime()));
            orderMapper.updateById(oldOrder);
            System.out.println("支付成功了？");
            mailService.payOrder(oldOrder);
            return "redirect:"+host+"/#/success/order/pay?id="+oldOrder.getId();
        }
        return "redirect:"+host+"/#/fail/order/pay";

    }

//    @UnLogin
    @ResponseBody
    @PostMapping("/refund")
    public Result<Object> refund(@RequestBody com.shopping.mall.core.module.order.entity.Order order){
        return paymentService.refund(order);
    }

    @UnLogin
    @ResponseBody
    @PostMapping("/refundAdmin")
    public Result<Object> refundAdmin(@RequestBody com.shopping.mall.core.module.order.entity.Order order){
        return paymentService.refundAdmin(order);
    }

}

